﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using WeifenLuo.WinFormsUI.Docking;
using Infragistics.Win;
using Infragistics.Win.UltraWinGrid;
using Infragistics.Excel;
namespace BYManageInfoSystem
{
    public partial class Frm_SQZL2CW : DockContent
    {

        private DGBY.BLL.HxdNoTab m_bllHxdNoTab = new DGBY.BLL.HxdNoTab();

        public Frm_SQZL2CW()
        {
            InitializeComponent();
        }
        private void SetTimeColumns(bool bCompute, DataTable dtTemp, int nIndex
            , string strColName, ref bool bIsNull, ref DateTime dtMax)
        {
            if (dtTemp.Rows[nIndex][strColName].ToString() != "")
            {
                DateTime dTimeTemp = (DateTime)dtTemp.Rows[nIndex][strColName];
                if (dTimeTemp.Year == 1900)
                {
                    dtTemp.Rows[nIndex][strColName] = DBNull.Value;
                    if (bCompute)
                        bIsNull = true;
                }
                else
                {
                    if (bCompute && dTimeTemp > dtMax)
                        dtMax = dTimeTemp;
                }
            }
            else
            {
                if (bCompute)
                    bIsNull = true;
            }
        }
        private void ShowAllRecord(string strWhere)
        {
            DataSet ds = m_bllHxdNoTab.ShowSQZL2CWRec(strWhere);
            DataTable dtTemp = ds.Tables[0];
           
            dtTemp.Columns.Add("显示最后日期", Type.GetType("System.DateTime"));
            dtTemp.Columns.Add("占用天数", Type.GetType("System.Int32"));
            //Dictionary<int, int> dicID2nIndex = new Dictionary<int, int>();
            for (int i = 0; i < dtTemp.Rows.Count; i++)
            {
       
                DateTime dtMax = DateTime.Parse("1900-01-01");
                bool bIsNull = false;

              
                SetTimeColumns(true, dtTemp, i, "录入发票日期", ref bIsNull, ref dtMax);
                SetTimeColumns(false, dtTemp, i, "增值税发票开票日期", ref bIsNull, ref dtMax);
                SetTimeColumns(true, dtTemp, i, "回收购货合同日期", ref bIsNull, ref dtMax);
                SetTimeColumns(false, dtTemp, i, "送货单日期", ref bIsNull, ref dtMax);
                SetTimeColumns(false, dtTemp, i, "收出口合同登记日期", ref bIsNull, ref dtMax);
                SetTimeColumns(false, dtTemp, i, "出口发票打印日期", ref bIsNull, ref dtMax);
                SetTimeColumns(true, dtTemp, i, "收到核销单日期", ref bIsNull, ref dtMax);
                SetTimeColumns(false, dtTemp, i, "已核销日期", ref bIsNull, ref dtMax);

   
                if (bIsNull)
                {
                    dtTemp.Rows[i]["显示最后日期"] = DBNull.Value;
                }
                else
                {
                    dtTemp.Rows[i]["显示最后日期"] = dtMax.Date;
                    if (dtTemp.Rows[i]["交财务退税资料单日期"].ToString() != "")
                    {
                        DateTime dTimeTemp = (DateTime)dtTemp.Rows[i]["交财务退税资料单日期"];
                        if (dTimeTemp.Year > 1900)
                        {
                            TimeSpan ts = dTimeTemp.Date - dtMax.Date;
                            dtTemp.Rows[i]["占用天数"] = ts.Days;

                        }
              
                    }
                }


            }

            ultraGrid1.DataSource = null;
            ultraGrid1.DataSource = dtTemp;

            if (Frm_Main.m_bCompleteVer == false)
            {
                foreach (UltraGridColumn ugc in ultraGrid1.DisplayLayout.Bands[0].Columns)
                {
                    ugc.Hidden = true;
                }
                ultraGrid1.DisplayLayout.Bands[0].Columns["申报年月"].Hidden = false;
                ultraGrid1.DisplayLayout.Bands[0].Columns["公司名称"].Hidden = false;
                ultraGrid1.DisplayLayout.Bands[0].Columns["部门"].Hidden = false;
                ultraGrid1.DisplayLayout.Bands[0].Columns["合同编号"].Hidden = false;
                ultraGrid1.DisplayLayout.Bands[0].Columns["工厂名称"].Hidden = false;
                ultraGrid1.DisplayLayout.Bands[0].Columns["币制"].Hidden = false;
                ultraGrid1.DisplayLayout.Bands[0].Columns["报关金额"].Hidden = false;
                ultraGrid1.DisplayLayout.Bands[0].Columns["交财务退税资料单日期"].Hidden = false;
                ultraGrid1.DisplayLayout.Bands[0].Columns["交财务退税资料单年月"].Hidden = false;
            }
            


      
            ultraGrid1.DisplayLayout.Bands[0].Columns[0].Hidden = true;
            //ultraGrid1.DisplayLayout.Bands[0].Columns[1].Hidden = true;
            //ultraGrid1.DisplayLayout.Bands[0].Columns[dtTemp.Columns.Count - 3].Hidden = true;
        }

        private void buttonShowAll_Click(object sender, EventArgs e)
        {
            ShowAllRecord("");
        }

        private void buttonExportExcel_Click(object sender, EventArgs e)
        {
            DataTable dt = (DataTable)ultraGrid1.DataSource;

            if (dt != null)
            {
                if (dt.Rows.Count > 0)
                {
                    SaveFileDialog sfd = new SaveFileDialog();
                    sfd.Filter = "Excel文件(*.xls)|*.xls";
                    string outFile = "";

                    if (sfd.ShowDialog() == DialogResult.OK)
                    {
                        outFile = sfd.FileName;
                    }
                    else
                    {
                        return;
                    }

                    ultraGridExcelExporter2.Export(ultraGrid1, outFile);
                }
            }
        }
        public static void ultraGrid1_InitializeRowFilter(Infragistics.Win.UltraWinGrid.InitializeLayoutEventArgs e)
        {
            //ultraGrid1.DisplayLayout.Override.RowSizing = RowSizing.AutoFree;
            //foreach (UltraGridColumn ugc in ultraGrid1.DisplayLayout.Bands[0].Columns)
            //    ugc.PerformAutoResize();
            // FILTER ROW FUNCTIONALITY RELATED ULTRAGRID SETTINGS
            //e.Layout.Override.RowFilterAction = RowFilterAction.DisableFilteredOutRows;
            // ----------------------------------------------------------------------------------
            // Enable the the filter row user interface by setting the FilterUIType to FilterRow.
            e.Layout.Override.FilterUIType = FilterUIType.FilterRow;
            //e.Layout.Override.RowFilterMode = RowFilterMode.AllRowsInBand;
            // FilterEvaluationTrigger specifies when UltraGrid applies the filter criteria typed 
            // into a filter row. Default is OnCellValueChange which will cause the UltraGrid to
            // re-filter the data as soon as the user modifies the value of a filter cell.
            e.Layout.Override.FilterEvaluationTrigger = FilterEvaluationTrigger.OnCellValueChange;
            //e.Layout.Override.RowFilterMode = RowFilterMode.AllRowsInBand;
            // By default the UltraGrid selects the type of the filter operand editor based on
            // the column's DataType. For DateTime and boolean columns it uses the column's editors.
            // For other column types it uses the Combo. You can explicitly specify the operand
            // editor style by setting the FilterOperandStyle on the override or the individual
            // columns.

            e.Layout.Override.FilterOperandStyle = FilterOperandStyle.DropDownList;

            // By default UltraGrid displays user interface for selecting the filter operator. 
            // You can set the FilterOperatorLocation to hide this user interface. This
            // property is available on column as well so it can be controlled on a per column
            // basis. Default is WithOperand. This property is exposed off the column as well.
            e.Layout.Override.FilterOperatorLocation = FilterOperatorLocation.WithOperand;

            // By default the UltraGrid uses StartsWith as the filter operator. You use
            // the FilterOperatorDefaultValue property to specify a different filter operator
            // to use. This is the default or the initial filter operator value of the cells
            // in filter row. If filter operator user interface is enabled (FilterOperatorLocation
            // is not set to None) then that ui will be initialized to the value of this
            // property. The user can then change the operator as he/she chooses via the operator
            // drop down.
            e.Layout.Override.FilterOperatorDefaultValue = FilterOperatorDefaultValue.StartsWith;

            // FilterOperatorDropDownItems property can be used to control the options provided
            // to the user for selecting the filter operator. By default UltraGrid bases 
            // what operator options to provide on the column's data type. This property is
            // avaibale on the column as well.
            //e.Layout.Override.FilterOperatorDropDownItems = FilterOperatorDropDownItems.All;

            // By default UltraGrid displays a clear button in each cell of the filter row
            // as well as in the row selector of the filter row. When the user clicks this
            // button the associated filter criteria is cleared. You can use the 
            // FilterClearButtonLocation property to control if and where the filter clear
            // buttons are displayed.
            e.Layout.Override.FilterClearButtonLocation = FilterClearButtonLocation.RowAndCell;

            // Appearance of the filter row can be controlled using the FilterRowAppearance proeprty.
            e.Layout.Override.FilterRowAppearance.BackColor = Color.LightYellow;

            // You can use the FilterRowPrompt to display a prompt in the filter row. By default
            // UltraGrid does not display any prompt in the filter row.
            e.Layout.Override.FilterRowPrompt = "Click here to filter data...";

            // You can use the FilterRowPromptAppearance to change the appearance of the prompt.
            // By default the prompt is transparent and uses the same fore color as the filter row.
            // You can make it non-transparent by setting the appearance' BackColorAlpha property 
            // or by setting the BackColor to a desired value.
            e.Layout.Override.FilterRowPromptAppearance.BackColorAlpha = Alpha.Opaque;

            // By default the prompt is spread across multiple cells if it's bigger than the
            // first cell. You can confine the prompt to a particular cell by setting the
            // SpecialRowPromptField property off the band to the key of a column.
            //e.Layout.Bands[0].SpecialRowPromptField = e.Layout.Bands[0].Columns[0].Key;

            // Display a separator between the filter row other rows. SpecialRowSeparator property 
            // can be used to display separators between various 'special' rows, including for the
            // filter row. This property is a flagged enum property so it can take multiple values.
            e.Layout.Override.SpecialRowSeparator = SpecialRowSeparator.FilterRow;

            // You can control the appearance of the separator using the SpecialRowSeparatorAppearance
            // property.
            e.Layout.Override.SpecialRowSeparatorAppearance.BackColor = Color.FromArgb(233, 242, 199);

            //   UltraGridBand band = e.Layout.Bands[0];
            //   band.ColumnFilters["原币金额"].FilterConditions.Clear();
            //   band.ColumnFilters["原币金额"].FilterConditions.Add(

            //FilterComparisionOperator.GreaterThan, 5);
            //   band.ColumnFilters["原币金额"].FilterConditions.Add(

            //FilterComparisionOperator.LessThan, 10);
            //   band.ColumnFilters["原币金额"].LogicalOperator = FilterLogicalOperator.And;
        }
        private void SetSumColumn(Infragistics.Win.UltraWinGrid.InitializeLayoutEventArgs e)
        {
            SummarySettings averageSummary =
e.Layout.Bands[0].Summaries.Add(
"报关金额",
SummaryType.Sum,
e.Layout.Bands[0].Columns["报关金额"]);
            averageSummary.SummaryPosition = SummaryPosition.UseSummaryPositionColumn;
            averageSummary.SummaryPositionColumn = averageSummary.SourceColumn;
            averageSummary.DisplayFormat = "{0:.##}";
            averageSummary.Band.Override.SummaryFooterCaptionVisible = DefaultableBoolean.False;
            averageSummary.Band.Override.BorderStyleSummaryFooter = UIElementBorderStyle.None;
            averageSummary.SummaryDisplayArea = SummaryDisplayAreas.TopFixed;

          
           
            averageSummary =
e.Layout.Bands[0].Summaries.Add(
"应退税额",
SummaryType.Sum,
e.Layout.Bands[0].Columns["应退税额"]);
            averageSummary.SummaryPosition = SummaryPosition.UseSummaryPositionColumn;
            averageSummary.SummaryPositionColumn = averageSummary.SourceColumn;
            averageSummary.DisplayFormat = "{0:.##}";
            averageSummary.Band.Override.SummaryFooterCaptionVisible = DefaultableBoolean.False;
            averageSummary.Band.Override.BorderStyleSummaryFooter = UIElementBorderStyle.None;
            averageSummary.SummaryDisplayArea = SummaryDisplayAreas.TopFixed;

            averageSummary =
e.Layout.Bands[0].Summaries.Add(
"实际退税额",
SummaryType.Sum,
e.Layout.Bands[0].Columns["实际退税额"]);
            averageSummary.SummaryPosition = SummaryPosition.UseSummaryPositionColumn;
            averageSummary.SummaryPositionColumn = averageSummary.SourceColumn;
            averageSummary.DisplayFormat = "{0:.##}";
            averageSummary.Band.Override.SummaryFooterCaptionVisible = DefaultableBoolean.False;
            averageSummary.Band.Override.BorderStyleSummaryFooter = UIElementBorderStyle.None;
            averageSummary.SummaryDisplayArea = SummaryDisplayAreas.TopFixed;

        
        }
        private void ultraGrid1_InitializeLayout(object sender, Infragistics.Win.UltraWinGrid.InitializeLayoutEventArgs e)
        {
            SetSumColumn(e);
            if (this.checkBox1.Checked == true)
                ultraGrid1_InitializeRowFilter(e);
            else
                ClassUltraGridCommonSet.ultraGrid1_InitializeRowFilter(e);

            ultraGrid1.DisplayLayout.Override.WrapHeaderText = Infragistics.Win.DefaultableBoolean.True;

            InitColumnWidth();
        }

        private void InitColumnWidth()
        {
            ultraGrid1.DisplayLayout.Bands[0].Columns["发票是否连合同号"].Width = 30;
            ultraGrid1.DisplayLayout.Bands[0].Columns["申报日期"].Width = 75;
            ultraGrid1.DisplayLayout.Bands[0].Columns["申报年月"].Width = 60;
            ultraGrid1.DisplayLayout.Bands[0].Columns["公司名称"].Width = 60;
            ultraGrid1.DisplayLayout.Bands[0].Columns["部门"].Width = 60;
            ultraGrid1.DisplayLayout.Bands[0].Columns["合同编号"].Width = 75;
            ultraGrid1.DisplayLayout.Bands[0].Columns["工厂名称"].Width = 60;
            ultraGrid1.DisplayLayout.Bands[0].Columns["财务人员"].Width = 60;
            ultraGrid1.DisplayLayout.Bands[0].Columns["币制"].Width = 40;
            ultraGrid1.DisplayLayout.Bands[0].Columns["报关金额"].Width = 90;
            ultraGrid1.DisplayLayout.Bands[0].Columns["应退税额"].Width = 90;
            ultraGrid1.DisplayLayout.Bands[0].Columns["实际退税额"].Width = 90;
            ultraGrid1.DisplayLayout.Bands[0].Columns["录入发票日期"].Width = 75;
            ultraGrid1.DisplayLayout.Bands[0].Columns["增值税发票开票日期"].Width = 75;
            ultraGrid1.DisplayLayout.Bands[0].Columns["回收购货合同日期"].Width = 75;
            ultraGrid1.DisplayLayout.Bands[0].Columns["送货单日期"].Width = 75;
            ultraGrid1.DisplayLayout.Bands[0].Columns["收出口合同登记日期"].Width = 75;
            ultraGrid1.DisplayLayout.Bands[0].Columns["出口发票打印日期"].Width = 75;
            ultraGrid1.DisplayLayout.Bands[0].Columns["收到核销单日期"].Width = 75;
            ultraGrid1.DisplayLayout.Bands[0].Columns["已核销日期"].Width = 75;
            ultraGrid1.DisplayLayout.Bands[0].Columns["交财务退税资料单日期"].Width = 75;
            ultraGrid1.DisplayLayout.Bands[0].Columns["交财务退税资料单年月"].Width = 60;
            ultraGrid1.DisplayLayout.Bands[0].Columns["是否开票完成"].Width = 45;
            ultraGrid1.DisplayLayout.Bands[0].Columns["交财务退税资料单年月"].Width = 60;
            ultraGrid1.DisplayLayout.Bands[0].Columns["是否开票完成"].Width = 45;
            ultraGrid1.DisplayLayout.Bands[0].Columns["显示最后日期"].Width = 75;
            ultraGrid1.DisplayLayout.Bands[0].Columns["占用天数"].Width = 45;
        }

        public void InitUltraWinGridSetting()
        {
            this.ultraGrid1.DisplayLayout.Override.RowSelectors = Infragistics.Win.DefaultableBoolean.True;
            this.ultraGrid1.DisplayLayout.Override.RowSelectorNumberStyle = Infragistics.Win.UltraWinGrid.RowSelectorNumberStyle.VisibleIndex;
            this.ultraGrid1.DisplayLayout.Override.RowSelectorWidth = 40;
        }
        private void Frm_SQZL2CW_Load(object sender, EventArgs e)
        {
            InitUltraWinGridSetting();
            this.button1.Visible = Frm_Main.m_bCompleteVer;
        }

        private void ultraGridExcelExporter1_BeginExport(object sender, Infragistics.Win.UltraWinGrid.ExcelExport.BeginExportEventArgs e)
        {
            //Worksheet ws = e.CurrentWorksheet;
            //int nColumn = 0;
            //ws.Rows[1].Cells[nColumn++].Value = "交财务退税资料单年月";
            //ws.Rows[1].Cells[nColumn++].Value = "工厂名称";
            //ws.Rows[1].Cells[nColumn++].Value = "报关金额";
            //ws.Rows[1].Cells[nColumn++].Value = "应退税额";
            //ws.Rows[1].Cells[nColumn++].Value = "实际退税额";

            //e.CurrentRowIndex = 2;
        }

        private void ultraGridExcelExporter1_CellExported(object sender, Infragistics.Win.UltraWinGrid.ExcelExport.CellExportedEventArgs e)
        {
             //Worksheet ws = e.CurrentWorksheet;
             //if (e.CurrentColumnIndex == 2)
             //{

             //}
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Infragistics.Win.UltraWinGrid.UltraGridRow[] ugr = ultraGrid1.Rows.GetFilteredInNonGroupByRows();
            if (ugr.Length <= 0)
            {
                return;
            }
            StringBuilder strSql = new StringBuilder();
            foreach (Infragistics.Win.UltraWinGrid.UltraGridBand band in this.ultraGrid1.DisplayLayout.Bands)
            {
                // since all rows in a band have the same filters in RowFilterMode.AllRowsInBand this
                // will clear the filters
                List<object> lstO= band.ColumnFilters.All.ToList();
                string strColumnName;
                string strColumnValue;
                foreach (object o in lstO)
                {
                    ColumnFilter cf = (ColumnFilter)o;
                    strColumnName = cf.Column.Key;
                    strColumnValue = cf.FilterConditions.Count > 0 ? ((FilterCondition)cf.FilterConditions.All[0]).CompareValue.ToString() : "";
                    if (strColumnName == "申报年月")
                    {
                        if (strColumnValue == "")
                            continue;
                        if (strSql.ToString() != "")
                        {
                            strSql.Append(" and ");
                        }

                        strSql.Append("CONVERT(varchar(6), HxdNoTab.SBDate, 112) = '" + strColumnValue + "'");
                
                    }
                    else if (strColumnName == "交财务退税资料单年月")
                    {
                        if (strColumnValue == "")
                            continue;
                        if (strSql.ToString() != "")
                        {
                            strSql.Append(" and ");
                        }

                        strSql.Append("CONVERT(varchar(6), HxdNoTab.JcwTszldDate, 112) = '" + strColumnValue + "'");
                    }
                    else if (strColumnName == "公司名称")
                    {
                        if (strColumnValue == "")
                            continue;
                        if (strSql.ToString() != "")
                        {
                            strSql.Append(" and ");
                        }

                        strSql.Append("BYCompanyTab.CompanyNameJX = '" + strColumnValue + "'");
                    }
                    else if (strColumnName == "部门")
                    {
                        if (strColumnValue == "")
                            continue;
                        if (strSql.ToString() != "")
                        {
                            strSql.Append(" and ");
                        }

                        strSql.Append("BYDepartTab.DepartName = '" + strColumnValue + "'");
                    }
                }

            }
            //string strFilterCondition = ugr[0].Cells["交财务退税资料单年月"].Value.ToString();
            //string strFilterCondition2 = ugr[0].Cells["申报年月"].Value.ToString();
            //DataSet ds = m_bllHxdNoTab.ShowSQZL2CWRecHuiZong("CONVERT(varchar(6), HxdNoTab.JcwTszldDate, 112) = '" + strFilterCondition + "' and CONVERT(varchar(6), HxdNoTab.SBDate, 112) = '" + strFilterCondition2 + "'");
            DataSet ds = m_bllHxdNoTab.ShowSQZL2CWRecHuiZong(strSql.ToString());
            DataTable dt = ds.Tables[0];
            ultraGrid2.DataSource = dt;
            if (dt != null)
            {
                if (dt.Rows.Count > 0)
                {
                    SaveFileDialog sfd = new SaveFileDialog();
                    sfd.Filter = "Excel文件(*.xls)|*.xls";
                    string outFile = "";

                    if (sfd.ShowDialog() == DialogResult.OK)
                    {
                        outFile = sfd.FileName;
                    }
                    else
                    {
                        return;
                    }

                    ultraGridExcelExporter1.Export(ultraGrid2, outFile);
                }
            }
        }

        private void ultraGrid1_BeforeRowUpdate(object sender, CancelableRowEventArgs e)
        {
            try
            {
                UltraGridRow CurrentUGR;
                CurrentUGR = ultraGrid1.Rows[e.Row.Index];

                ModifyGoodsDetail(e.Row.Index);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                e.Cancel = true;
            }
        }

        private bool ModifyGoodsDetail(int nRowIndex)
        {
            try
            {
                UltraGridRow CurrentUGR;
                CurrentUGR = ultraGrid1.Rows[nRowIndex];
                int nSelectID = Convert.ToInt32(CurrentUGR.Cells[0].Value.ToString(), 10);
                DGBY.Model.HxdNoTab modelHxdNoTabb = m_bllHxdNoTab.GetModel(nSelectID);

                modelHxdNoTabb.bitInvoiceWithContract = Convert.ToBoolean(CurrentUGR.Cells["发票是否连合同号"].Value.ToString());

                m_bllHxdNoTab.Update(modelHxdNoTabb);
                Frm_Main.Log2DB(this.Text, "修改", modelHxdNoTabb.HxdNoTabID.ToString());

                return true;

            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.ToString(), "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
        }
    }
}
